package com.mb.solr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mb.solr.bo.SolrProductBO;
import com.mb.solr.service.ISolrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * Solr服务实现
 * @author
 * @create 2019-04-09 7:59 PM
 **/

@Service("solrService")
@ConfigurationProperties()
@Slf4j
public class SolrServiceImpl implements ISolrService {

    @Value("${spring.data.solr.host}")
    private String host;
    @Value("${spring.data.solr.core}")
    private String core;

    private static SolrClient solr;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getCore() {
        return core;
    }

    public void setCore(String core) {
        this.core = core;
    }

    private HttpSolrClient connetHttpSolrClientServer(){
        return new HttpSolrClient.Builder(host + "/" + core)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();
    }

    /**
     *@ClassDescribe:向solr插入数据
     *@author:chenxi
     *@param input 数据封装
     * @return
     */
    @Override
    public boolean pushDataIntoSolr( SolrInputDocument input) {
        boolean flag = false;
        try {
            solr = connetHttpSolrClientServer();
            solr.add(input);
            solr.commit();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            try {
                solr.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
        return flag;
    }


    /**
     *@ClassDescribe:按条件查询搜索引擎
     *@author:chenxi
     *@param query solr查询条件
     *@return 返回查询集合
     */
    @Override
    public SolrDocumentList querySolrIndex(String query) {
        SolrDocumentList list = null;
        try {
            solr = connetHttpSolrClientServer();
            QueryResponse rsp = null;
            SolrQuery queryStr = new SolrQuery("*:*");
            queryStr.addFilterQuery(query);
            rsp = solr.query(queryStr);
            list = rsp.getResults();
        } catch (IOException | SolrServerException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            try {
                solr.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
        return list;
    }

    @Override
    public void deleteById(String id) {
        try {
            solr = connetHttpSolrClientServer();
            solr.deleteById(id);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteProduct(Long productId) {
        try {
            solr = connetHttpSolrClientServer();
            solr.deleteByQuery("productId:"+productId);
            solr.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean updateProduct(SolrProductBO productBO) {
        if(productBO == null){
            return false;
        }

        log.info("updateProduct :"+ JSONObject.toJSONString(productBO));
        // 定义数据 solr输入文档 数据结构为Map
        SolrInputDocument inputDocument = new SolrInputDocument();
        inputDocument.addField("productId",productBO.getProductId().toString());
        inputDocument.addField("productName", productBO.getProductName());
        inputDocument.addField("productDesc", productBO.getProductDesc());
        inputDocument.addField("color", productBO.getColorArr());
        inputDocument.addField("specs", productBO.getSpecsArr());
        inputDocument.addField("updateTime", new Date());
        inputDocument.addField("id", productBO.getId());
        return this.pushDataIntoSolr(inputDocument);
    }
}
